'''4G信号强度'''
import re
import redis
from setting import CABINET_CURRENT_RSSI_4G

import logging

logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger(__name__)

import serial
import time

class Rssi4G:

    def __enter__(self):

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):

        self.ser.close()

    def __init__(self) -> None:

        # 配置串行端口
        self.ser = serial.Serial(
            port='/dev/ttyUSB2',  # 串行端口，Windows中可能是COM数字，如COM3
            baudrate=9600,        # 波特率，根据您的设备调整
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS,
            timeout=1              # 超时设置
        )

        # # 检查串行端口是否已打开
        # if self.ser.is_open:
        #     self.ser.close()

        # # 打开串行端口
        # self.ser.open()

    def get_rssi_value(self):

        '''获取rssi值'''

        # 发送AT命令
        self.ser.write(b"AT+CSQ\r\n")
        time.sleep(1)  # 等待响应

        # 读取响应
        response = self.ser.read(self.ser.in_waiting).decode('utf-8').rstrip()

        regex = '\+CSQ: (.*?),.*?'

        rssi = re.findall(regex, response)

        r = redis.Redis(host='localhost', port=6379, db=0)

        if rssi:

            r.set(CABINET_CURRENT_RSSI_4G, rssi[0])

            logger.info("CABINET_CURRENT_RSSI_4G: {}".format(rssi[0]))

            return rssi[0]
        
        else:

            r.set(CABINET_CURRENT_RSSI_4G, "0")

            logger.info("CABINET_CURRENT_RSSI_4G: {}".format(0))

            return None


if __name__ == "__main__":

    with Rssi4G() as rssi:

        rssi.get_rssi_value()


